package com.youfang.sixthmedia.common;

import android.app.Application;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;

/**
 * 百度地图服务
 * 
 * @author teddy
 * 
 */
public class BaiduMapApplication extends Application {

	public static final String MAP_KEY = "369025EA5256A1275F02CADC2B1008ED13170528";

	// //////////////地图服务部分////////////////////////
	// //////////////////////////////////////////////
	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	protected BMapManager mBMapMan = null;
	protected boolean m_bKeyRight = true; // 授权Key正确，验证通过

	class MapMyGeneralListener implements MKGeneralListener {
		@Override
		public void onGetNetworkState(int iError) {
			Toast.makeText(BaiduMapApplication.this.getApplicationContext(),
					"您的网络出错啦！", Toast.LENGTH_LONG).show();
		}

		@Override
		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误：
				Toast.makeText(
						BaiduMapApplication.this.getApplicationContext(),
						"地图服务授权Key验证失败！", Toast.LENGTH_LONG).show();
				BaiduMapApplication.this.m_bKeyRight = false;
			}
		}
	}

	private MapMyGeneralListener mapListener = new MapMyGeneralListener();

	public BaiduMapApplication ensureMananger() {
		if (this.mBMapMan == null) {
			this.createMapService();
		}
		return this;
	}

	public void enableAllProviders() {
		this.mBMapMan.getLocationManager().enableProvider(
				MKLocationManager.MK_GPS_PROVIDER);
		this.mBMapMan.getLocationManager().enableProvider(
				MKLocationManager.MK_NETWORK_PROVIDER);

	}

	public boolean isMapServiceReady() {
		return this.m_bKeyRight;

	}

	public BMapManager getMapManager() {
		return mBMapMan;
	}

	public void setManager(BMapManager mBMapMan) {
		this.mBMapMan = mBMapMan;

	}

	public void setmBMapMan(BMapManager mBMapMan) {
		this.mBMapMan = mBMapMan;
	}

	public boolean isM_bKeyRight() {
		return m_bKeyRight;
	}

	public void setM_bKeyRight(boolean m_bKeyRight) {
		this.m_bKeyRight = m_bKeyRight;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.createMapService();

	}

	@Override
	public void onTerminate() {
		super.onTerminate();
		destroyMapService();
	}

	public void stopMapService() {
		this.mBMapMan.stop();
	}

	public void startMapService() {
		this.mBMapMan.start();
	}

	protected void createMapService() {
		mBMapMan = new BMapManager(this);
		mBMapMan.init(MAP_KEY, mapListener);

	}

	protected void destroyMapService() {
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}

	}
}
